import sqlite3 
import sys
import json
import os
import threading
from funcs import *
from PyQt5.QtWidgets import QWidget,QVBoxLayout,QHBoxLayout,QPushButton,QMainWindow,QApplication,QStyleFactory,QLabel,QTextEdit,QTreeWidget,QTreeWidgetItem,QLineEdit,QAction,qApp,QTabWidget,QComboBox,QTableWidget,QListWidget,QListWidgetItem,QCheckBox,QTableWidgetItem
from PyQt5.Qt import QFont,QIcon,QAbstractItemView,QRegExp,QRegExpValidator
db = "dictation.db"
dictDbName = "dict.db"
dictSource = sqlite3.connect(dictDbName)
dictConn = sqlite3.connect(":memory:")
dictSource.backup(dictConn)
conn = sqlite3.connect(db)
cur = conn.cursor()
class taskAdder(QWidget):
	def __init__(self):
		super().__init__()
		self.getSourceTables()
		self.initUI()
		self.updateSourceTables(isChecked=True)
	def initUI(self):
		mainV = QVBoxLayout()
		topH = QHBoxLayout()
		workV = QVBoxLayout()
		typeH = QHBoxLayout()
		testCountH = QHBoxLayout()
		modeH = QHBoxLayout()
		intervalH = QHBoxLayout()
		submitH = QHBoxLayout()

		self.rangeList = QListWidget()

		typeLabel = QLabel("类型")
		self.typeBox = QComboBox()
		self.typeBox.addItems(["拼音","字词"])
		self.typeBox.currentIndexChanged.connect(self.switchType)
		self.type = 0
		typeH.addWidget(typeLabel)
		typeH.addStretch(1)
		typeH.addWidget(self.typeBox)

		testCountLable = QLabel("测试个数")
		self.testCountEdit = QLineEdit("60")
		self.testCountEdit.setVisible(False)
		testCountH.addWidget(testCountLable)
		testCountH.addStretch(1)
		testCountH.addWidget(self.testCountEdit)

		modeLabel = QLabel("模式")
		self.modeBox = QComboBox()
		self.modeBox.addItems(["扫盲","扫盲+有限个数","纠错","全局","生成测试文档","生成释义","生成多音字"])
		self.modeBox.currentIndexChanged.connect(self.switchMode)
		modeH.addWidget(modeLabel)
		modeH.addStretch(1)
		modeH.addWidget(self.modeBox)
		self.mode = 0

		submitButton = QPushButton("创建任务")
		submitButton.clicked.connect(self.submit)
		submitH.addWidget(submitButton)
		submitH.addStretch(1)

		workV.addLayout(typeH)
		workV.addLayout(testCountH)
		workV.addLayout(modeH)
		workV.addLayout(submitH)

		topH.addLayout(workV)
		topH.addWidget(self.rangeList)
		topH.addStretch(1)

		mainV.addLayout(topH)
		mainV.addStretch(1)

		self.setLayout(mainV)
	def switchType(self,i):
		self.type = i
		self.getSourceTables()
		self.updateSourceTables(isChecked=True)
	def switchMode(self,i):
		if i == 1:
			self.testCountEdit.setVisible(True)
		else:
			self.testCountEdit.setVisible(False)
		if i == 4:
			self.updateSourceTables(isChecked=False)
		else:
			self.updateSourceTables(isChecked=True)
		self.mode = i
	def getSourceTables(self):
		self.sourceTableNameLists = {0:[],1:[]}
		for table in readTableF(cur,"mgr"):
			self.sourceTableNameLists[table["type"]].append(table["tableName"])
	def updateSourceTables(self,isChecked):
		self.selectBoxList = []
		self.rangeList.clear()
		for tableName in self.sourceTableNameLists[self.type]:
			box = QCheckBox(tableName)
			box.setChecked(isChecked)
			item = QListWidgetItem()
			self.rangeList.addItem(item)
			self.rangeList.setItemWidget(item,box)
			self.selectBoxList.append(box)
	def submit(self):
		tm1 = time.time()
		createTaskTable(cur)
		count = self.testCountEdit.text().strip()
		destsourceList = []
		filename = time.strftime("%Y-%m-%d-%H-%M-%S")
		if self.mode == 2:
			for tableName,i in zip(self.sourceTableNameLists[self.type],range(len(self.sourceTableNameLists[self.type]))):
				if self.selectBoxList[i].isChecked():
					tmpsourceList = getFaultSourceList(cur,tableName)
					destsourceList = destsourceList + tmpsourceList
			random.shuffle(destsourceList)
		elif self.mode == 3:
			for tableName,i in zip(self.sourceTableNameLists[self.type],range(len(self.sourceTableNameLists[self.type]))):
				if self.selectBoxList[i].isChecked():
					tmpsourceList = getSourceList(cur,tableName)
					destsourceList = destsourceList + tmpsourceList
			random.shuffle(destsourceList)
		elif self.mode == 4:
			tmpListList = []
			tableNameList = []
			for tableName,i in zip(self.sourceTableNameLists[self.type],range(len(self.sourceTableNameLists[self.type]))):
				if self.selectBoxList[i].isChecked():
					tmpListList.append(getSourceList(cur,tableName))
					tableNameList.append(tableName)
			t = threading.Thread(target=writeTestDoc,args=(tmpListList,"、".join(tableNameList)+" %d张表的测试文档"%len(tableNameList),tableNameList))
			t.start()
			self.showMessage("已生成测试文档")
			return
		elif self.mode == 5:
			tmpListList = []
			tableNameList = []
			for tableName,i in zip(self.sourceTableNameLists[self.type],range(len(self.sourceTableNameLists[self.type]))):
				if self.selectBoxList[i].isChecked():
					tmpListList.append(getSourceList(cur,tableName))
					tableNameList.append(tableName)
			t = threading.Thread(target=writeDescDoc,args=(tmpListList,"、".join(tableNameList)+" %d张表的释义文档文档"%len(tableNameList),tableNameList))
			t.start()
			self.showMessage("已生成释义文档")
			return
		elif self.mode == 6:
			tableNameList = []
			for tableName,i in zip(self.sourceTableNameLists[self.type],range(len(self.sourceTableNameLists[self.type]))):
				if self.selectBoxList[i].isChecked():
					tmpsourceList = getSourceList(cur,tableName)
					destsourceList = destsourceList + tmpsourceList
					tableNameList.append(tableName)
			t = threading.Thread(target=genMulDoc,args=(destsourceList,filename,0))
			t.start()
			self.showMessage("已生成多音字文档")
			return
		else:
			for tableName,i in zip(self.sourceTableNameLists[self.type],range(len(self.sourceTableNameLists[self.type]))):
				if self.selectBoxList[i].isChecked():
					tmpsourceList = getUnsolvedSourceList(cur,tableName)
					destsourceList = destsourceList + tmpsourceList
			if self.mode == 0:
				random.shuffle(destsourceList)
			elif self.mode == 1:
				if len(count) == 0:
					self.showMessage("无个数")
					return
				destsourceList = getLimitedSourceList(destsourceList,int(count))
				random.shuffle(destsourceList)
		destLen = len(destsourceList)
		if destLen != 0:
			filename += "个数" + str(destLen)
			recordList = genRecordList(destsourceList)
			t = threading.Thread(target=genSourceQADoc,args=(destsourceList,filename,self.type))
			t.start()	
			genTask(conn,cur,recordList,filename,self.type)
			self.showMessage("成功创建，长度："+str(len(recordList))+"用时"+str(time.time()-tm1))
		else:
			self.showMessage("无符合条件数据集")
	def showMessage(self,msg):
		self.parent().parent().parent().statusBar().showMessage(msg)
class accomplishTaskWidget(QWidget):
	def __init__(self):
		super().__init__()
		self.loadExistedSource()
		self.getTasks()
		self.initUI()
		self.updateTasks()
	def initUI(self):
		taskLabel = QLabel("已有任务")
		sub2Label = QLabel("当前错误")
		self.mistakeEdit = QTextEdit()
		submitButton = QPushButton("提交任务")
		submitButton.clicked.connect(self.submit)
		self.table = QTableWidget(0,6)
		self.table.setHorizontalHeaderLabels(["是否错误","汉字源","汉字","拼音","表格名","id"])
		self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.taskList = QListWidget()
		self.taskList.clicked.connect(self.selectTask)

		mainV = QVBoxLayout()
		topH = QHBoxLayout()
		taskV = QVBoxLayout()
		mistakeV = QVBoxLayout()
		sub1H = QHBoxLayout()
		sub2H = QHBoxLayout()

		sub1H.addWidget(taskLabel)
		sub1H.addStretch(1)

		taskV.addLayout(sub1H)
		taskV.addStretch(1)
		taskV.addWidget(self.taskList)
		taskV.setStretch(0,1)
		taskV.setStretch(1,3)

		sub2H.addWidget(sub2Label)
		sub2H.addStretch(1)

		mistakeV.addLayout(sub2H)
		mistakeV.addStretch(1)
		mistakeV.addWidget(self.mistakeEdit)
		mistakeV.setStretch(0,1)
		mistakeV.setStretch(1,3)

		topH.addLayout(taskV)
		topH.addStretch(1)
		topH.addLayout(mistakeV)
		topH.setStretch(0,5)
		topH.setStretch(1,2)


		submitH = QHBoxLayout()
		submitH.addStretch(1)
		submitH.addWidget(submitButton)

		mainV.addLayout(topH)
		mainV.addWidget(self.table)
		mainV.addLayout(submitH)
		self.setLayout(mainV)
	def loadExistedSource(self):
		self.existedSource = {}
		for row in readTableF(cur,"mgr"):
			self.existedSource[row["tableName"]] = {}
			for r in readTableF(cur,row["tableName"]):
				sourceItem = json.loads(r["sourceItem"])
				self.existedSource[row["tableName"]][r["id"]] = sourceItem
	def getTasks(self):
		createTaskTable(cur)
		self.taskQueryList = []
		for row in readTableF(cur,"task"):
			row["recordList"] = json.loads(row["recordList"])
			for recordItem in row["recordList"]:
				recordItem["pass"]=True #每一个未提交的词语都正确
			self.taskQueryList.append(row)
		self.currentTaskId = -1
	def updateTasks(self):
		self.taskList.clear()
		for row in self.taskQueryList:
			typeTag = {}
			typeTag[0] = "拼音"
			typeTag[1] = "字形"
			item = QListWidgetItem("%s 个数=%d 类型=%s"%(row["filename"],row["count"],typeTag[row["type"]]))
			self.taskList.addItem(item)
	def updateRecords(self,taskId):
		self.currentTaskId = taskId
		self.table.setRowCount(0)
		self.table.clearContents()
		self.checkBoxes = []
		tRecordList = []
		for rc in self.taskQueryList[taskId]["recordList"]:
			row = self.table.rowCount()
			self.table.setRowCount(row + 1)
			t = rc["t"]
			id = rc["id"]
			checkBox = QCheckBox()
			checkBox.clicked.connect(self.updateWrong)
			self.checkBoxes.append(checkBox)
			if id in self.existedSource[t]:
				sourceItem = self.existedSource[t][id]
				sHan = ""
				sPy = ""
				for pinyinItem in sourceItem["pinyin"]:
					sHan = sHan + sourceItem["han"][pinyinItem["i"]]+" "
					sPy = sPy + pinyinItem["py"] +" "
				tRecordList.append([sourceItem["han"],sHan,sPy,t,str(id)])
			else:
				tRecordList.append(["null","null","null","null",str(0)])
		tRecordListLen = len(tRecordList)
		for tRecordItem,i in zip(tRecordList,range(tRecordListLen)):
			self.table.setCellWidget(i,0,self.checkBoxes[i])
			for j in range(5):
				self.table.setItem(i,j+1,QTableWidgetItem(tRecordItem[j]))
	def selectTask(self,item):
		self.updateRecords(item.row())
	def updateWrong(self):
		self.wrongSourceList = []
		for cb,i in zip(self.checkBoxes,range(len(self.checkBoxes))):
			if cb.isChecked():
				#在每一条record内添加错误history，再在updateSourceState内加在history列表的末尾
				self.taskQueryList[self.currentTaskId]["recordList"][i]["pass"]=False
				recordItem = self.taskQueryList[self.currentTaskId]["recordList"][i]
				t = recordItem["t"]
				id = recordItem["id"]
				sourceItem = self.existedSource[t][id]
				self.wrongSourceList.append(sourceItem)
		wrongText = ""
		for wrongSourceItem,i in zip(self.wrongSourceList,range(len(self.wrongSourceList))):
			wrongText = wrongText + "[%d]%s"%(i+1,wrongSourceItem["han"]+" ")
		self.mistakeEdit.setText(wrongText)
	def showMessage(self,msg):
		self.parent().parent().parent().statusBar().showMessage(msg)
	def submit(self):
		self.table.setRowCount(0)
		self.table.clearContents()
		if self.currentTaskId < len(self.taskQueryList) and self.currentTaskId >= 0 :
			updateSourceState(conn,cur,self.taskQueryList[self.currentTaskId]["recordList"],self.taskQueryList[self.currentTaskId]["id"])
		else:
			self.showMessage("未选择")
			return
		self.getTasks()
		self.updateTasks()
		self.mistakeEdit.clear()
		self.showMessage("提交成功")
class sourceCreateWidget(QWidget):
	def __init__(self):
		super().__init__()
		self.loadExistedSource()
		self.initUI()
	def initUI(self):
		self.sourceList = []
		mainV = QVBoxLayout()
		workH = QHBoxLayout()
		inputV = QVBoxLayout()
		reviewV = QVBoxLayout()
		tableH = QHBoxLayout()
		similarV = QVBoxLayout()
		similarLabelH = QVBoxLayout()
		py1H = QHBoxLayout()
		py2H = QHBoxLayout()
		py3H = QHBoxLayout()
		pycH = QHBoxLayout()
		hanH = QHBoxLayout()
		commitH = QHBoxLayout()
		addButton = QPushButton("添加词语")
		clearButton = QPushButton("清除输入框")
		clearallButton = QPushButton("清除全部")
		insertButton = QPushButton("添加到数据库")
		addButton.clicked.connect(self.addWord)
		insertButton.clicked.connect(self.insert)
		clearButton.clicked.connect(self.clear)
		clearallButton.clicked.connect(self.clearall)

		reg = QRegExp("^[0-9\\.]+$")
		validator = QRegExpValidator(self)
		validator.setRegExp(reg)

		tableLabel = QLabel("数据表名")
		tableTypeLabel = QLabel("种类")
		hanLabel = QLabel("词组")
		py1Label = QLabel("拼音1")
		py2Label = QLabel("拼音2")
		py3Label = QLabel("拼音3")
		pycLabel = QLabel("共同拼音")
		#dictInfo
		self.dictListWidget = QListWidget()
		#similar
		similarLabel = QLabel("相似源")
		self.similarTable = QTableWidget()
		self.similarTable = QTableWidget(0,5)
		self.similarTable.setHorizontalHeaderLabels(["汉字源","汉字","拼音","表格","id"])
		for i in range(5):
			self.similarTable.horizontalHeader().resizeSection(i,100)
		self.similarTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
		#json
		self.jsonEdit = QTextEdit("json样例")
		f = QFont("微软雅黑")
		f.setPixelSize(f.pointSize()*3)
		self.jsonTree = QTreeWidget()
		self.jsonTree.setFont(f)
		self.jsonTree.setColumnCount(2)
		self.jsonTree.setHeaderLabels(['key','value'])
		self.jsonTree.setColumnWidth(0,300)
		self.rootItem = QTreeWidgetItem()
		self.rootItem.setText(0,"root")
		self.updateTree()
		self.jsonEdit.setText(json.dumps(self.sourceList))

		self.hanEdit = QLineEdit("")
		self.hanEdit.textChanged.connect(self.updateWordRelations)
		self.tableEdit = QLineEdit("")
		self.tableTypeBox = QComboBox()
		self.tableTypeBox.addItems(["拼音","字词"])
		self.tableTypeBox.currentIndexChanged.connect(self.switchType)
		self.type = 0
		self.py1Edit = QLineEdit("")
		self.py2Edit = QLineEdit("")
		self.py3Edit = QLineEdit("")
		self.pycEdit = QLineEdit("")
		self.py1iEdit = QLineEdit("")
		self.py1iEdit.setValidator(validator)
		self.py2iEdit = QLineEdit("")
		self.py2iEdit.setValidator(validator)
		self.py3iEdit = QLineEdit("")
		self.py3iEdit.setValidator(validator)
		self.pyciEdit = QLineEdit("")
		self.pyciEdit.setValidator(validator)

		hanH.addWidget(hanLabel)
		hanH.addStretch(1)
		hanH.addWidget(self.hanEdit)

		tableH.addWidget(tableLabel)
		tableH.addStretch(1)
		tableH.addWidget(self.tableEdit)
		tableH.addWidget(tableTypeLabel)
		tableH.addWidget(self.tableTypeBox)

		py1H.addWidget(py1Label)
		py1H.addStretch(1)
		py1H.addWidget(self.py1Edit)
		py1H.addWidget(self.py1iEdit)

		py2H.addWidget(py2Label)
		py2H.addStretch(1)
		py2H.addWidget(self.py2Edit)
		py2H.addWidget(self.py2iEdit)

		py3H.addWidget(py3Label)
		py3H.addStretch(1)
		py3H.addWidget(self.py3Edit)
		py3H.addWidget(self.py3iEdit)

		pycH.addWidget(pycLabel)
		pycH.addStretch(1)
		pycH.addWidget(self.pycEdit)
		pycH.addWidget(self.pyciEdit)

		commitH.addWidget(clearButton)
		commitH.addWidget(clearallButton)
		commitH.addStretch(1)
		commitH.addWidget(addButton)
		commitH.addWidget(insertButton)

		similarLabelH.addWidget(similarLabel)
		similarLabelH.addStretch(1)

		similarV.addLayout(similarLabelH)
		similarV.addWidget(self.similarTable)

		inputV.addLayout(tableH)
		inputV.addLayout(hanH)
		inputV.addLayout(py1H)
		inputV.addLayout(py2H)
		inputV.addLayout(py3H)
		inputV.addLayout(pycH)
		inputV.addLayout(commitH)
		inputV.addStretch(1)
		inputV.addWidget(self.dictListWidget)
		inputV.addLayout(similarV)


		reviewV.addWidget(self.jsonTree)
		reviewV.addWidget(self.jsonEdit)
		reviewV.setStretch(0,4)
		reviewV.setStretch(1,1)

		workH.addLayout(reviewV)
		workH.addLayout(inputV)

		mainV.addLayout(workH)

		self.setLayout(mainV)
	def addWord(self):
		tmpSourceItem = {}
		tmpSourceItem["pinyin"] = []
		isPy = False
		hans = self.hanEdit.text().strip()
		pyc = self.pycEdit.text().strip()
		pyci = self.pyciEdit.text().strip()
		py1 = self.py1Edit.text().strip()
		py1i = self.py1iEdit.text().strip()
		py2 = self.py2Edit.text().strip()
		py2i = self.py2iEdit.text().strip()
		py3 = self.py3Edit.text().strip()
		py3i = self.py3iEdit.text().strip()
		if(len(hans)!=0):
			tmpSourceItem["han"]= hans
		else:
			self.showMessage("无汉字")
			return
		if(len(pyc)!=0 and len(pyci)!=0):
			for i in pyci.split("."):
				if i != "":
					if int(i)-1>=len(hans):
						self.showMessage("拼音下标越界")
						return
					tmp = {}
					tmp["py"]=pyc
					tmp["i"]=int(i)-1
					tmpSourceItem["pinyin"].append(tmp)
			isPy = True
		if(len(py1)!=0 and len(py1i)!=0):
			for i in py1i.split("."):
				if i != "":
					if int(i)-1>=len(hans):
						self.showMessage("拼音下标越界")
						return
					tmp = {}
					tmp["py"]=py1
					tmp["i"]=int(i)-1
					tmpSourceItem["pinyin"].append(tmp)
			isPy = True
		if(len(py2)!=0 and len(py2i)!=0):
			for i in py2i.split("."):
				if i != "":
					if int(i)-1>=len(hans):
						self.showMessage("拼音下标越界")
						return
					tmp = {}
					tmp["py"]=py2
					tmp["i"]=int(i)-1
					tmpSourceItem["pinyin"].append(tmp)
			isPy = True
		if(len(py3)!=0 and len(py3i)!=0):
			for i in py3i.split("."):
				if i != "":
					if int(i)-1>=len(hans):
						self.showMessage("拼音下标越界")
						return
					tmp = {}
					tmp["py"]=py3
					tmp["i"]=int(i)-1
					tmpSourceItem["pinyin"].append(tmp)
			isPy = True
		if isPy == False:
			self.showMessage("无拼音")
			return
		def takeIndex(e):
			return e["i"]
		if self.samePyList != None:
			tmpSourceItem["pinyin"] += self.samePyList
			tmpSourceItem["cover"] = True
			tmpSourceItem["id"] = self.sameId
			tmpSourceItem["tableName"] = self.sameTableName
		else:
			tmpSourceItem["cover"] = False
		tmpSourceItem["pinyin"].sort(key=takeIndex)
		tmpSourceItem["en"]= tmpSourceItem["pinyin"][0]["py"]
		self.sourceList.append(tmpSourceItem)
		self.updateTree()
		self.jsonEdit.setText(json.dumps(self.sourceList))
		self.jsonTree.scrollToBottom()
	def clearall(self):
		self.sourceList = []
		self.hanEdit.clear()
		self.py1Edit.clear()
		self.py2Edit.clear()
		self.py3Edit.clear()
		self.py1iEdit.clear()
		self.py2iEdit.clear()
		self.py3iEdit.clear()
		self.pycEdit.clear()
		self.pyciEdit.clear()
		self.updateTree()
		self.jsonEdit.setText(json.dumps(self.sourceList))
		self.focusHan()
	def clear(self):
		self.hanEdit.clear()
		self.py1Edit.clear()
		self.py2Edit.clear()
		self.py3Edit.clear()
		self.py1iEdit.clear()
		self.py2iEdit.clear()
		self.py3iEdit.clear()
		self.pyciEdit.clear()
		self.focusHan()
	def insert(self):
		tableName = self.tableEdit.text().strip()
		#表类型
		if(len(tableName)==0):
			self.showMessage("未输入表名或种类")
			return
		if(self.sourceList == []):
			self.showMessage("空数据不能插入表")
			return
		self.showMessage("")
		createTableMgr(cur)
		createSourceTable(cur,tableName)
		#添加mgr链接
		if(checkTableLink(cur,tableName) == False):
			addTableLink(conn,cur,tableName,self.type)
		insertSourceList(conn,cur,tableName,self.sourceList)
		self.loadExistedSource()
		self.clearall()
	def updateTree(self):
		for i in range(self.rootItem.childCount()):
			self.rootItem.removeChild(self.rootItem.child(0))
		for py in self.sourceList:
			childPy = QTreeWidgetItem()
			childEn = QTreeWidgetItem()
			childHan = QTreeWidgetItem()
			childPinyin = QTreeWidgetItem()
			childEn.setText(0,"en")
			childEn.setText(1,py["en"])
			childHan.setText(0,"han")
			childHan.setText(1,py["han"])
			childPy.addChild(childEn)
			childPy.addChild(childHan)
			targetStr = ""
			for item in py["pinyin"]:
				pyName = QTreeWidgetItem()
				pyName.setText(0,"py")
				pyName.setText(1,item["py"])
				pyName.setIcon(1,QIcon("iconbmp/Apply.bmp"))
				childPinyin.addChild(pyName)
				targetStr = targetStr +py["han"][item["i"]]
			childPinyin.setText(1,targetStr)
			childPinyin.setText(0,"目标拼音")
			childPinyin.setIcon(1,QIcon("iconbmp/Ok.bmp"))
			childPy.addChild(childPinyin)
			self.rootItem.addChild(childPy)
		self.jsonTree.addTopLevelItem(self.rootItem)
		self.jsonTree.expandAll()
	def loadExistedSource(self):
		self.existedSource = {0:{},1:{}}
		for row in readTableF(cur,"mgr"):
			self.existedSource[row["type"]][row["tableName"]] = {}
			for r in readTableF(cur,row["tableName"]):
				sourceItem = json.loads(r["sourceItem"])
				self.existedSource[row["type"]][row["tableName"]][r["id"]] = sourceItem
				topId = r["id"]
			self.existedSource[row["type"]][row["tableName"]]["topId"] = topId
	def updateWordRelations(self,msg):
		self.similarTable.setRowCount(0)
		self.similarTable.clearContents()
		self.dictListWidget.clear()
		currentHan = msg.strip()
		if(len(currentHan)==0):
			return
		similarList = []
		self.samePyList = None
		self.sameTableName = None
		self.sameId = None
		for table in self.existedSource[self.type]:
			for lineId in self.existedSource[self.type][table]:
				if lineId == "topId":
					continue
				
				sourceItem = self.existedSource[self.type][table][lineId]
				if sourceItem["han"].find(currentHan) != -1 or currentHan.find(sourceItem["han"]) != -1:
					sHan = ""
					sPy = ""
					for pyItem in sourceItem["pinyin"]:
						sHan = sHan + sourceItem["han"][pyItem["i"]]+" "
						sPy = sPy + pyItem["py"] +" "
					similarList.append([sourceItem["han"],sHan,sPy,table,str(lineId)])
					if sourceItem["han"] == currentHan:
						self.samePyList = sourceItem["pinyin"]
						self.sameTableName = table
						self.sameId = lineId
		similarListLen = len(similarList)
		self.similarTable.setRowCount(similarListLen)
		for similarItem,i in zip(similarList,range(similarListLen)):
			for j in range(5):
				self.similarTable.setItem(i,j,QTableWidgetItem(similarItem[j]))
		dictCur = dictConn.cursor()
		for row in readTableFW(dictCur,"xdDict","han like '%s'"%("%"+msg+"%")):
			tmpListItem = QListWidgetItem("【现代】"+row["description"])
			self.dictListWidget.addItem(tmpListItem)
		for row in readTableFW(dictCur,"cyDict","han like '%s'"%("%"+msg+"%")):
			tmpListItem = QListWidgetItem("【成语】"+row["description"])
			self.dictListWidget.addItem(tmpListItem)
	def focusHan(self):
		self.hanEdit.setFocus()
	def focusPy1(self):
		self.py1Edit.setFocus()
	def focusPyc(self):
		self.pycEdit.setFocus()
	def focusPy1i(self):
		self.py1iEdit.setFocus()
	def focusPyci(self):
		self.pyciEdit.setFocus()
	def focusTable(self):
		self.tableEdit.setFocus()
	def redoWord(self):
		lenSourceList = len(self.sourceList)
		if (lenSourceList == 0):
			self.showMessage("队列已空")
			return
		self.sourceList.pop(lenSourceList-1)
		self.updateTree()
		self.jsonTree.scrollToBottom()
		self.jsonEdit.setText(json.dumps(self.sourceList))
	def showMessage(self,msg):
		self.parent().parent().parent().statusBar().showMessage(msg)
	def switchType(self,i):
		self.type = i
class settingsWidget(QWidget):
	def __init__(self):
		super().__init__()
		self.initUI()
	def initUI(self):
		mainV = QVBoxLayout()

		removeTasksH = QHBoxLayout()
		removeTasksLabel = QLabel("清除所有任务")
		removeTasksButton = QPushButton("清除所有任务")
		removeTasksButton.clicked.connect(self.removeTasks)
		removeTasksH.addWidget(removeTasksLabel)
		removeTasksH.addStretch(1)
		removeTasksH.addWidget(removeTasksButton)		

		removeHistoryH = QHBoxLayout()
		removeHistoryLabel = QLabel("清除所有历史")
		removeHistoryButton = QPushButton("清除所有历史")
		removeHistoryButton.clicked.connect(self.removeHistory)
		removeHistoryH.addWidget(removeHistoryLabel)
		removeHistoryH.addStretch(1)
		removeHistoryH.addWidget(removeHistoryButton)

		mainV.addLayout(removeTasksH)
		#mainV.addLayout(removeHistoryH)
		mainV.addStretch(1)
		self.setLayout(mainV)
	def removeHistory(self):
		clearAllHistory(conn,cur)
		self.showMessage("清除完毕")
	def removeTasks(self):
		cur.execute("delete from task")
		self.showMessage("清除完毕")
	def showMessage(self,msg):
		self.parent().parent().parent().statusBar().showMessage(msg)